from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django import http
from django.contrib.auth import login, authenticate, logout, mixins
from django_redis import get_redis_connection
from django.conf import settings

from meiduo_mall.utils.response_code import RETCODE
from .models import User
import re, json
from django.views import View
from .utils import generate_verify_email_url, check_verify_email_token
from celery_tasks.email.tasks import send_verify_email
from .models import Address
from meiduo_mall.utils.views import LoginRequiredView
from goods.models import SKU
from carts.utils import merge_cart_cookie_to_redis


class RegisterView(View):
    """用户注册"""

    def get(self, request):

        return render(request, 'register.html')

    def    post(self, request):
        """注册业务逻辑"""
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        password2 = query_dict.get('password2')
        mobile = query_dict.get('mobile')
        sms_code = query_dict.get('sms_code')  # 短信验证
        allow = query_dict.get('allow')

        # 校验数据
        # 判断参数是否齐全
        if all([username, password, password2, mobile, sms_code, allow]) is False:
            return http.HttpResponseForbidden('校验参数不足')

        # 判断用户名是否是5～20位
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5到20位用户名')

        # 判断密码是否是5～8个
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8到15位密码')

        if password2 != password:
            return http.HttpResponseForbidden('两次输入密码不一致')

        # 判断手机号是否11位
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的11位号码')

        # 连接数据库
        redis_conn = get_redis_connection('verify_code')
        # 获取redis中短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        # 判断验证码是否过期
        if sms_code_server is None:
            return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})

        # 删除redis中已被使用过的短信验证
        redis_conn.delete('sms_%s' % mobile)

        # 由bytes转换为str decode()编码
        # sms_code_server = sms_code_server.decode()
        # 判断用户输入的短信验证码是否正确
        if sms_code != sms_code_server.decode():
            return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        # 业务逻辑处理
        user = User.objects.create_user(username=username, password=password, mobile=mobile)

        # 用户注册成功后即代表登录,需要做状态保持本质是将当前用户的id存储到session
        login(request, user)

        response = redirect('/')
        # 状态保持
        response.set_cookie('username', user.username, max_age=settings.SESSION_COOKIE_AGE)
        # 响应
        return response


class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class LoginView(View):
    """用户名登入"""

    def get(self, request):
        """展示登入界面"""
        return render(request, 'login.html')

    def post(self, request):
        """实现用户登入"""
        # 接收请求体中的表单数据
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        remembered = query_dict.get('remembered')

        # 登入认证authen#ticate：认证（username=用户, password=密码）
        user = authenticate(request, username=username, password=password)

        if user is None:  # 如果if成立说明用户登入失败
            return render(request, 'login.html', {'account_errmsg': '用户名或者密码错误'})

        # 状态保持
        login(request, user)

        # 判断用户是否勾选记住登入
        if remembered is None:
            # session默认过期时间是两周，0代表浏览器关闭session就清除
            request.session.set_expiry(0)

        response = redirect(request.GET.get('next', '/'))
        response.set_cookie('username', user.username, max_age=(settings.SESSION_COOKIE_AGE if remembered else None))

        merge_cart_cookie_to_redis(request, response)
        # 登入成功重定向到首页
        return response


class LoginOut(View):
    """退出登陆"""

    def get(self, request):
        """实现退出登陆逻辑"""
        # 清理session
        logout(request)
        # 退出登陆重定向到首页
        response = redirect('/login/')
        # 退出登陆时清除cookie中username
        response.delete_cookie('username')
        return response


# class UserInfo(View):
#     """展示用户中心"""
#     def get(self, request):
#         """提供个人用户中心"""
#         # 判断用户是否登陆
#         if request.user.is_authenticated():
#             return render(request, 'user_center_info.html')
#         else:
#             # 返回登陆界面
#             return redirect('/login/?next=/info/')


class UserInfo(mixins.LoginRequiredMixin, View):
    """展示用户中心"""

    def get(self, request):
        """提供个人用户中心"""
        return render(request, 'user_center_info.html')


class EmailView(LoginRequiredMixin, View):
    """设置用户email"""

    def put(self, request):
        # 1.接收参数
        json_str = request.body.decode()  # body返回的是bytes
        json_dict = json.loads(json_str)  # 将字符串转换成json字典模式
        email = json_dict.get('email')

        # 2.校验email
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('email错误')

        # 3.获取当前登入用户user模型对象
        user = request.user
        # 修改email给email赋值
        User.objects.filter(username=user.username, email='').update(email=email)
        # 生成email结果url
        verify_url = generate_verify_email_url(user)
        # celery进行异步发送邮件
        send_verify_email.delay(email, verify_url)

        # 4.响应添加email结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加email成功'})


class VerifyEmailView(View):
    """激活邮箱"""

    def get(self, request):
        # 获取url中的参数
        token = request.GET.get('token')

        # 校验参数： 判断token是否为空和过期，提取user
        if token is None:
            return http.HttpResponseForbidden('缺少token参数')

        # 对token进行解密并查询到要激活邮箱的那个用户
        user = check_verify_email_token(token)

        # 日过没有查到提前响应
        if user is None:
            return http.HttpResponseForbidden('token无效')

        # 如果查询到user,修改它的email_active字段为True,再save()
        user.email_active = True
        user.save()

        # 响应
        return redirect('/info/')


class AddressView(LoginRequiredMixin, View):
    """用户收货地址展示"""

    def get(self, request):
        """提供收货地址界面"""
        # 获取用户地址列表
        user = request.user
        # 查询出来当前用户的所有未被逻辑删除的收货地址
        addresses = Address.objects.filter(user=user, is_deleted=False)

        # 把查询集里面的模型转换成字典,然后再添加到列表中
        addresses_list = []
        for address_model in addresses:
            addresses_list.append({
                'id': address_model.id,
                'title': address_model.title,
                'receiver': address_model.receiver,
                'province_id': address_model.province_id,
                'province': address_model.province.name,
                'city_id': address_model.city_id,
                'city': address_model.city.name,
                'district_id': address_model.district_id,
                'district': address_model.district.name,
                'place': address_model.place,
                'mobile': address_model.mobile,
                'tel': address_model.tel,
                'email': address_model.email
            })

        # 获取到用户默认收货地址的id
        default_address_id = user.default_address_id
        # 包装要传入模型的渲染数据
        context = {
            'default_address_id': default_address_id,
            'addresses': addresses_list,
        }
        return render(request, 'user_center_site.html', context)


class CreateAddressView(View):
    """新增用户地址"""

    def post(self, request):

        # 判断用户当前收货地址的数量.不能超过20个
        count = Address.objects.filter(user=request.user, is_deleted=False).count()

        if count >= 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '收货地址数量上限'})

        # 接受请求提.body参数
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 新增收货地址
        address_model = Address.objects.create(
            user=request.user,
            title=title,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )

        # 如果当前用户还没有默认收货地址,就把当前新增的收货地址直接设置为它的默认地址
        if request.user.default_address is None:
            request.user.default_address = address_model
            request.user.save()

        # 把新增的收货地址再转换成字典响应回去
        address_dict = {
            'id': address_model.id,
            'title': address_model.id,
            'receiver': address_model.receiver,
            'province_id': address_model.province_id,
            'province': address_model.province.name,
            'city_id': address_model.city_id,
            'city': address_model.city.name,
            'district_id': address_model.district_id,
            'district': address_model.district.name,
            'place': address_model.place,
            'mobile': address_model.mobile,
            'tel': address_model.tel,
            'email': address_model.email
        }

        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加地址成功', 'address': address_dict})


class UpdateDestroyAddressView(LoginRequiredMixin, View):
    """收货地址修改和删除"""
    def put(self, request, address_id):
        """修改地址"""
        # 接受请求体,body数据
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 查询出要修改的模型对象
        try:
            address_model = Address.objects.get(id=address_id, user=request.user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id无效')
        address_model.title = title
        address_model.receiver = receiver
        address_model.province_id = province_id
        address_model.city_id = city_id
        address_model.district_id = district_id
        address_model.place = place
        address_model.mobile = mobile
        address_model.tel = tel
        address_model.email = email
        # 如果使用update去修改数据时,auto_now 不会重新赋值,如果是调用save做的修改数据,才会对auto_now 进行重新赋值
        address_model.save()

        # 把修改后的的收货地址再转换成字典响应回去
        address_dict = {
            'id': address_model.id,
            'title': address_model.title,
            'receiver': address_model.receiver,
            'province_id': address_model.province_id,
            'province': address_model.province.name,
            'city_id': address_model.city_id,
            'city': address_model.city.name,
            'district_id': address_model.district_id,
            'district': address_model.district.name,
            'place': address_model.place,
            'mobile': address_model.mobile,
            'tel': address_model.tel,
            'email': address_model.email,
        }

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改收货地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除收货地址"""
        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id无效')

        # 删除逻辑
        address.is_deleted = True
        address.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '收货地址删除成功'})


class UpdateAddressTitleView(LoginRequiredView):
    """修改收货地址标题"""
    def put(self, request, address_id):
        # 接收前段传入的新标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id无效')

        address.title = title
        address.save()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class DefaultAddressView(LoginRequiredMixin, View):
    """设置用户默认收货地址"""
    def put(self, request, address_id):
        """设置默认地址"""
        # 查询指定id的收货地址,并校验
        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id无效')

        # 获取当前user模型对象
        user = request.user
        # 给user的default_address 重写赋值
        user.default_address = address
        user.save()
        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class ChangePasswordView(LoginRequiredView):
    """修改用户密码"""
    def get(self, request):
        return render(request, 'user_center_pass.html')

    def post(self, request):
        """修改密码逻辑"""
        # 接收请求中的表单数据
        old_pwd = request.POST.get('old_pwd')
        new_pwd = request.POST.get('new_pwd')
        new_cpwd = request.POST.get('new_cpwd')

        # 校验
        if all([old_pwd, new_pwd, new_cpwd]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        user = request.user
        if user.check_password(old_pwd) is False:
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码错误'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_pwd):
            return http.HttpResponseForbidden('密码最少8位，最长20位')
        if new_pwd != new_cpwd:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        # 修改用户密码
        user.set_password(new_pwd)
        user.save()

        return redirect('/logout/')


class UserBrowseHistory(View):
    """商品浏览记录"""
    def post(self, request):
        """保存用户浏览记录"""
        if request.user.is_authenticated:
            # 获取请求提中的sku_id
            json_dict = json.loads(request.body.decode())
            sku_id = json_dict.get('sku_id')

            # 校验参数
            try:
                sku = SKU.objects.get(id=sku_id)
            except SKU.DoesNotExist:
                return http.HttpResponseForbidden('sku_id不存在')

            # 创建redis链接对象
            redis_conn = get_redis_connection('history')
            pl = redis_conn.pipeline()

            # 获取当前登录用户
            user = request.user
            key = 'history_%s' % user.id

            pl.lrem(key, 0, sku_id)
            pl.lpush(key, sku_id)
            pl.ltrim(key, 0, 4)
            pl.execute()

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
        else:
            return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})

    def get(self, request):
        """获取用户浏览器记录"""
        # 判断当前用户是否登录
        if request.user.is_authenticated:
            # 创建链接redis对象
            redis_conn = get_redis_connection('history')
            # lrange获取当前用户在redis中存储的浏览器记录sku_id
            sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)
            # 用来装每一个sku的字典
            sku_list = []
            # 通过sku_id查询出对应的sku模型
            for sku_id in sku_ids:
                sku = SKU.objects.get(id=sku_id)
                sku_list.append({
                    'id': sku.id,
                    'name': sku.name,
                    'default_image_url': sku.default_image.url,
                    'price': sku.price
                })
            # 把sku模型转换成字典,在添加到列表中,注意商品的顺序
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': sku_list})
        else:
            # 如果没有登入,响应其他
            return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '未登录用户', 'skus': []})